<?php

function sql_injection($content){
//	static $recur_num = 0;
//	if(++$recur_num > 4) {
//		//echo 'array too deep';
//		return;
//	}
	if (!get_magic_quotes_gpc()){
		if (is_array($content)){
			foreach ($content as $key => $value) {
				$query[$key] = sql_injection($value);//$content[addslashes($key)] = addslashes($value);				
			}
		}else{
			$query = addslashes($content);
		}
	}
	$query = str_replace(array('%'), array('\%'), $query);
	return $query;
}



function filtrateQuery( $query, $debar ){
	$querys = explode('&',$query);
	$urls = '';
	foreach($querys as $query){
		$query = explode('=',$query);
		$urls[$query[0]] = $query[1] ;
	}
	$query = '';
	foreach($urls as $key => $url){
		foreach( $debar as $val){
			if(  $key != $val )
				$query .= $key .'='. $url .'&';		
		}
	}
	if( substr($query,strlen($query)-1) == '&' )
		$query = substr($query,0,strlen($query)-1);
	return $query;
}


function ip(){
/*	if($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
		$ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
	elseif($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])    
		$ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
	elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])       
		$ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];  
	elseif (getenv("HTTP_X_FORWARDED_FOR"))          
		$ip = getenv("HTTP_X_FORWARDED_FOR");  
	elseif (getenv("HTTP_CLIENT_IP"))                
		$ip = getenv("HTTP_CLIENT_IP");  
	elseif (getenv("REMOTE_ADDR"))                   
		$ip = getenv("REMOTE_ADDR"); 
	else                                           
		$ip = "0.0.0.0";
	return $ip;*/
	
	
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
		$ip = getenv('HTTP_CLIENT_IP');
	}elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
		$ip = getenv('REMOTE_ADDR');
	}elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	return preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown';
}



function htmlShow( $out ,$allowedTags  = '' ){	//$allowedTags  = '<a><br><b><img>'
	//$out = strip_tags( $out , $allowedTags );
	
	
	// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
	$out = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $out);
	
	$replaceArray = array(
		'style='  ,'%20' , '%27' ,'&#'
	);
	$toArray = array(
		'style.=' ,''	 , '' 	 ,'&amp;#'
	);
	//<img src="1.jpg" onclick="javascrip&#99;:alert(1)" style="background:url(javascript:alert(1));" />
	$out =  str_replace($replaceArray, $toArray , $out );
	
	//disabled attributes
	$disabledattributes = array(
	'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate',
	'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange',
	'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged',
	'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave',
	'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin',
	'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown',
	'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend',
	'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart',
	'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart',
	'onstop', 'onsubmit', 'onunload');
	$out = preg_replace('/\s('.implode('|', $disabledattributes).').*?([\s\>])/', '\\2', preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/javascript:[^\"\']*/i', '/(".implode('|', $disabledattributes).")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($out, $allowedTags)));
	  
	
	return  $out;
/*function RemoveXSS($val) {
   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
   // this prevents some character re-spacing such as <java\0script>
   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
   $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
   
   // straight replacements, the user should never need these since they're normal characters
   // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      // ;? matches the ;, which is optional
      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
   
      // &#x0040 @ search for the hex values
      $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      // &#00064 @ 0{0,7} matches '0' zero to seven times
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   
   // now the only remaining whitespace attacks are \t, \n, and \r
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   
   $found = true; // keep replacing as long as the previous round replaced something
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[xX]0{0,8}([9ab]);)';
               $pattern .= '|';
               $pattern .= '|(&#0{0,8}([9|10|13]);)';
               $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
         if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
         }
      }
   }
   return $val;
}*/
}

function toText( $out ){
	//$out = str_replace( "<p>" , "<p><_fridaying_>" ,$out )  ;
	//$out = str_replace( "<br />" , "<br />|_fridaying_|" ,$out )  ;
	//$out = strip_tags( $out );
	$out = str_replace(  '<' , "&lt;" , $out );
	$out = str_replace(  '>' , "&gt;" , $out );
	$out = str_replace(  '\"' , '&quot;' , $out );
	$out = str_replace(  '"' , '&quot;' , $out ); 
	$out = str_replace(  '\\\\' , '\\' , $out );
	//$out = str_replace(  chr(13) , " " , $out );
	//$out = str_replace(  chr(10) , " " , $out );
	//$out = str_replace( "|_fridaying_|" , "" ,$out )  ;
	return $out;	
}






function text2html( $out )
{
	$out = str_replace( " " , "&nbsp;" , $out );
	$out = str_replace( "　" , "&nbsp;" , $out );
	$out = str_replace(  chr(13) , "<br />" , $out );
	$out = str_replace(  chr(10) , "<br />" , $out );
	$txt = preg_replace("/[\r\n]{1,}/isU","<br/>\r\n",$txt);
	return $out;
}
 
function MySubStr($str, $sublen)
{
	if(strlen($str)<=$sublen) {
		$rStr = $str;
	} else {
		$I = 0;
		$sublen = $sublen * 3;
		while ($I<$sublen) {
			$StringTMP = substr($str,$I,1);
			
			if (ord($StringTMP)>=224) {
				$StringTMP = substr($str,$I,3);
				$I = $I + 3;
			} elseif (ord($StringTMP)>=192) {
				$StringTMP = substr($str,$I,2);
				$I = $I + 2;
			} else {
				$I = $I + 1;
			}
			
			$StringLast[] = $StringTMP;
		}
		
		$rStr = implode("",$StringLast).'...';
	} 
	
	return $rStr;
}



//utf-8中文截取，单字节截取模式
function subString($str, $length, $start=0){
	if(strlen($str) < $start+1){
		return '';
	}
	preg_match_all("/./su", $str, $ar);
	$str = '';
	$tstr = '';

	//为了兼容mysql4.1以下版本,与数据库varchar一致,这里使用按字节截取
	for($i=0; isset($ar[0][$i]); $i++){
		if(strlen($tstr) < $start){
			$tstr .= $ar[0][$i];
		}else{
			if(strlen($str) < $length + strlen($ar[0][$i]) ){
				$str .= $ar[0][$i];
			}else{
				break;
			}
		}
	}
	return $str;
}

function fileSizeFormat($filesize){
	if($filesize >= 1073741824){
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	}elseif($filesize >= 1048576){
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	}elseif($filesize >= 1024){
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	}else{
		$filesize = $filesize . ' Bytes';
	}
	return $filesize;
}



function getScriptName(){
	$Now_Path = array();
	$Now_Path = explode( '/' , $_SERVER['SCRIPT_NAME']);
	$Now_Path_Count = count($Now_Path);
	$Now_New_Path = '';
	for($i = 1; $i < $Now_Path_Count-1; $i++ ){		 
		$Now_New_Path  .= '/'. $Now_Path[$i];
	}
	return urlRewrite( $_SERVER['QUERY_STRING']) ;

}

function getPages($page,$total,$fileUrl,$pageSize=10,$pageLen=10,$pageRewrite = true){
	
	$pagecode = '';
	$page = intval($page);
	$total = intval($total);
	if(!$total) return ;
	$pages = ceil($total/$pageSize);
	if($page<1) $page = 1;
	if($page>$pages) $page = $pages;
	$offset = $pageSize*($page-1);
	$init = 1;
	$max = $pages;
	$pageLen = ($pageLen%2)?$pageLen:$pageLen+1;
	$pageoffset = ($pageLen-1)/2;
	
	//html
	 
	
	
	$pagecode='<div class="pages">';
	if($page!=1){
		if($pageRewrite){
			$pagecode.='<a href="'.$fileUrl.'-1.html">|<</a>';
			$pagecode.='<a href="'.$fileUrl.'-'.($page-1).'.html"><</a>';
		}else{
			$pagecode.='<a href="'.$fileUrl.'&page=1">|<</a>';
			$pagecode.='<a href="'.$fileUrl.'&page='.($page-1).'"><</a>';
		}
		
	}
	if($pages>$pageLen){
		if($page<=$pageoffset){
			$init=1;
			$max = $pageLen;
		}else{
			if($page+$pageoffset>=$pages+1){
				$init = $pages-$pageLen+1;
			}else{	
				$init = $page-$pageoffset;
				$max = $page+$pageoffset;
			}
		}
	}
	//生成html
	for($i=$init;$i<=$max;$i++){
		if($i==$page){
			$pagecode.='<span class="action">'.(($i - 1) *  $pageSize ).'</span>';
		} else {
			if($pageRewrite){
				$pagecode.="<a href=\"{$fileUrl}-".$i .".html\">".(($i - 1) *  $pageSize )."</a>";
			}else{
				$pagecode.="<a href=\"{$fileUrl}&page=".$i ."\">".(($i - 1) *  $pageSize )."</a>";
			}
		}
	}
	
	
//	for($i=$init;$i<=$max;$i++){
//		if($i==$page){
//			$pagecode.='<span class="action">'.(($i - 1) *  $pageSize + 1) .'-'. ($i *  $pageSize ).'</span>';
//		} else {
//			if(IS_REWRITE){
//				$pagecode.="<a href=\"{$fileUrl}-".$i .".html\">".(($i - 1) *  $pageSize + 1) .'-'. ($i *  $pageSize ) ."</a>";
//			}else{
//				$pagecode.="<a href=\"{$fileUrl}&page=".$i ."\">".(($i - 1) *  $pageSize + 1) .'-'. ($i *  $pageSize ) ."</a>";
//			}
//		}
//	}
//	
	
	
	if($page!=$pages){
		if($pageRewrite){
			$pagecode.='<a href="'.$fileUrl.'-'.($page+1).'.html">></a>';
			$pagecode.='<a href="'.$fileUrl.'-'.$pages.'.html">>|</a>';
		}else{
			$pagecode.='<a href="'.$fileUrl.'&page='.($page+1).'">></a>';
			$pagecode.='<a href="'.$fileUrl.'&page='.$pages.'">>|</a>';
		}
	}
	
	$pagecode.='<span class="totalPages"><strong>'. $page .'</strong>/'.$pages .' '. lang_page .'</span>';
	if( $pages == 1) $pagecode = '<div class="pages">';
	$pagecode.='</div>';
	//return array('pagecode'=>$pagecode,'sqllimit'=>' limit '.$offset.','.$pageSize);
	return $pagecode ;
}


function getImgHeight($image) {
	$size = getimagesize($image);
	$height = $size[1];
	return $height;
}

function getImgWidth($image) {
	$size = getimagesize($image);
	$width = $size[0];
	return $width;
}



function password($pass){
	$keyPrefixFlag = keyPrefixFlag;
	return sha1( $keyPrefixFlag . sha1( $keyPrefixFlag . $pass ));
}

	
function outClientCssFile($cssFile,$and='|'){
	foreach( explode($and,$cssFile) as $file ){
		echo '<link href="'.$file.'" rel="stylesheet" media="all" />';
	}
}

function outClientJsFile($jsFile,$and='|'){
	foreach( explode($and,$jsFile) as $file){
		echo '<script type="text/javascript" src="'. $file .'"></script>';
	}
}

function isEmail($email){	
	//return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
	
	if (eregi("^[_.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$",$email)){
		return true;	
	}else{ 
		return false;	
	} 
}



function remotePost($url , $data , $echo = false){
	//$data=array('foo'=>'bar'); 
	//$data = http_build_query($data);
	$opts = array( 
		'http'=>array( 
			'method'=>'POST', 
			'header'=>"Content-type: application/x-www-form-urlencoded\r\n". 
			"Content-Length: ".strlen($data)."\r\n", 
			'content' => $data 
		),
	); 
	$context = stream_context_create($opts); 
	$html = file_get_contents($url,false, $context); 
	if($echo)
		echo $html ;
	else	
		return $html; 
}

/*
class newFold(){
	var $upload_dir = date("Y/m/d");
	if(!is_dir($this->upload_dir)){
		$this->mkdir_r($this->upload_dir,0777);
	}
	function mkdir_r($dirName, $rights=0777){
		$dirs = explode('/', $dirName);
		$dir='';
		foreach ($dirs as $part) {
			$dir.=$part.'/';
			if (!is_dir($dir) && strlen($dir)>0)
				mkdir($dir, $rights);
		}
	}
}


*/





////////////////////  photo

function getHeight($image) {
	$size = getimagesize($image);
	$height = $size[1];
	return $height;
}

function getWidth($image) {
	$size = getimagesize($image);
	$width = $size[0];
	return $width;
}
function resizeImage($image,$width,$height,$scale) {
	list($imagewidth, $imageheight, $imageType) = getimagesize($image);
	$imageType = image_type_to_mime_type($imageType);
	$newImageWidth = ceil($width * $scale);
	$newImageHeight = ceil($height * $scale);
	$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
	switch($imageType) {
		case "image/gif":
			$source=imagecreatefromgif($image); 
			break;
	    case "image/pjpeg":
		case "image/jpeg":
		case "image/jpg":
			$source=imagecreatefromjpeg($image); 
			break;
	    case "image/png":
		case "image/x-png":
			$source=imagecreatefrompng($image); 
			break;
  	}
	imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
	
	switch($imageType) {
		case "image/gif":
	  		imagegif($newImage,$image); 
			break;
      	case "image/pjpeg":
		case "image/jpeg":
		case "image/jpg":
	  		imagejpeg($newImage,$image,90); 
			break;
		case "image/png":
		case "image/x-png":
			imagepng($newImage,$image);  
			break;
    }
	
	chmod($image, 0777);
	return $image;
}

function getFileExt($file_name){   
	$extend = explode("." , $file_name);   
	$type = $extend[count($extend)-1];
	$badType = explode(',',BAD_FILE_TYPE);
	if(in_array( $type , $badType ))
		$type = $type .'.design';
	return strtolower($type);   
}


function creatFolder($parentPath){
	$year	= date('Y',time()) . DS;
	$month	= date('m',time())	;
	$day	= date('d',time()) .DS ;
	$yearPath	= $parentPath . $year ;
	$dayPath	= $yearPath . $month . $day ;
	if( !file_exists( $yearPath ) )
		mkdir ( $yearPath , 0774 );
	if( !file_exists( $dayPath   ) )
		mkdir ( $dayPath , 0774 );
	return $year . $month . $day ;
}

function getPageFileUrl( $query = '' , $isRewrite = false){ 
	$host = 'http://'.$_SERVER['SERVER_NAME'];
	if( 80 != $_SERVER["SERVER_PORT"] )
		$host .= ':'.$_SERVER["SERVER_PORT"];
	$option = isset($_POST['option'])	?	$_POST['option'] : $_GET['option'] ;
	$nowurl = '?option='. $option ;
	//$nowurl = str_replace( 'index.php' , '' ,$host . $nowurl );
	//
	$url = filtrateQuery( $_SERVER['QUERY_STRING'] .'&'.$query, array('page') );
	if( $isRewrite )
		$url = urlRewrite($url);
	else
		$url =  '?'.$url ;
	return $url ; 
}


function getQuery($query){
	return isset($_POST[$query]) ? $_POST[$query] : (isset($_GET[$query]) ? $_GET[$query] : NULL);
}



function infoPage($body , $jumpUrl = '', $jumpTime  = 3){
	
	if( '' == $jumpUrl)
		$jumpUrl= $_SERVER['HTTP_REFERER'];
	$html = '<!DOCTYPE HTML>
		<html>
		<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="refresh" content="'. $jumpTime.';url='. $jumpUrl .'">
		<title>提示</title>
		<link href="'. THEME_PATH .'css/main.css" rel="stylesheet" media="all" />
		<script type="text/javascript">setTimeout(function(){
		window.location.href="'. $jumpUrl .'";},'. ($jumpTime * 1000 + 200) .');</script>
		</head>
		<body>';
	echo $html;
	include(ROOTPATH .'templates'. DS .'top.php');
	$html = '<div class="pos">
				<div class="contents">
					<div style=" padding:50px 100px 100px 30px;">
				'.$body ;
		if($jumpTime != 9999)
			$html .= '<p class="loading"></p>
					</div>';
	
	$html .= '
				</div>
			</div>';
	echo $html;
	include(ROOTPATH .'templates'. DS .'footer.php');
	$html ='</body>'
		.'</html>';
	echo $html;
}



function creatSelectList($obj,$start =0,$end=12,$step=1,$selectedNum=0){
	$html = '<select name="'.$obj.'" id="'.$obj.'">';
    for($i = $start; $i <=$end ; $i+=$step){
		if($i == $selectedNum ) $selected =' selected '; else $selected ='';
		$ii = $i;
		if( strlen($ii) == 1 ) $ii = '0'. $ii;
		$html .= '<option value="'. $ii .'"'.$selected.'>'. $ii .'</option>';
	}
    $html .= '</select>';
	return $html;
}


class rc4{
	var $keyword =  KEYWORD;
	function encrypt($pt,$type='') {
		$key = $this -> keyword ;//;
		$s = array();
		for ($i=0; $i<256; $i++) {
			$s[$i] = $i;
		}
		$j = 0;
		$x;
		for ($i=0; $i<256; $i++) {
			$j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
			$x = $s[$i];
			$s[$i] = $s[$j];
			$s[$j] = $x;
		}
		$i = 0;
		$j = 0;
		$ct = '';
		$y;
		for ($y=0; $y<strlen($pt); $y++) {
			$i = ($i + 1) % 256;
			$j = ($j + $s[$i]) % 256;
			$x = $s[$i];
			$s[$i] = $s[$j];
			$s[$j] = $x;
			$ct .= $pt[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
		}
		if('' == $type)
			$ct = base64_encode( $ct );
		return $ct;
	}
	function decrypt($ct){
		$key = $this -> keyword ;//;
		$ct =  base64_decode( $ct );
		return self::encrypt($ct,'recode');
	}	
}



class encrypt{
	var $keyword = KWYWORD ;// 密钥
	function code($encode){
		global  $aes;
		$key = $this -> keyword ;
		$keys = $aes->makeKey($key);
		$ct = $aes->encryptString($encode, $keys);
		return $ct;
	}	
	function recode($ct){
		global  $aes;
		$key  = $this -> keyword ;
		$keys = $aes -> makeKey($key);
		$cpt  = $aes -> decryptString($ct, $keys);
		//if( !$cpt )
		//	$cpt = 0 ;
		return $cpt;
	}
}


function  replaceBom( $str ){  
    $charset [1] =  substr ( $str ,0,1);  
    $charset [2] =  substr ( $str ,1,1);  
    $charset [3] =  substr ( $str ,2,1);  
    if  (ord( $charset [1]) == 239 && ord( $charset [2]) == 187 && ord( $charset [3]) == 191)  
    	return   substr ( $str ,3);
	else
		return $str; 
}

function urlRewrite( $url = ''){
	if(!$url)
		return ROOT_PATH;

	if( IS_REWRITE ){
		$urls = '';
		$type = '';
		$querys = explode('&',$url);
		foreach($querys as $query){
			$query = explode('=',$query);
			$urls[$query[0]] = $query[1] ;
		}
		$type = $urls['option'];
		$reUrl = '/';
		$i = 0 ;
		if( $type == 'creatMedia' ){
			foreach($urls as $key => $url){
				if( $i == 0 )
					$reUrl = $url ;
				if( $i == 1 )
					$reUrl .= '/'. $key .':'. $url ;
				$i++;
			}			
		}elseif( $type == 'attachment'){
			//option=attachment&mediaType=file&id='. $media_id_Code.'&page='.($i+1).
			foreach($urls as $key => $url){
				$space = ($i == 1 ||$i == 0 || $i == 2) ? '/' : '-';
				$reUrl .= $space. $url ;
				$i++;
			}			
		}else{
			foreach($urls as $key => $url){
				if( !$url) continue ;
				$space = ($i == 1 || $i == 0  ) ? '/' : '-';
				$reUrl .= $space. $url ;
				$i++;
			}	
		}		
		$reUrl = str_replace('//','',$reUrl);				
		return WEB_ROOT_PATH . $reUrl ;	
	}else
		return ROOT_PATH.'?'.$url ;
}


?>